package view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import control.Supervisorio;

import util.JNumberField;
import util.MyTable;
import view.component.basecomponent.pojo.ComponentPojo;
import entities.Action;
import entities.Variable;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
@SuppressWarnings("serial")
public class VariableWindow extends javax.swing.JFrame {
	private JPanel pnlBody;
	private JTabbedPane pnlAbas;
	private JPanel abaGeral;
	private JTextField txtName;
	private JButton btnExcluir;
	private JButton btnAdd;
	private JPanel pnlAcoesSul;
	private MyTable tblAcoes;
	private JScrollPane jScrollPane1;
	private JPanel pnlAcoes;
	private JSeparator jSeparator1;
	private JPanel jPanel1;
	private JTextPane jTextPane1;
	private JButton botaoOk;
	private JNumberField campoValor;
	private JButton btnUndo;
	private JTextPane txtDescricao;
	private JNumberField txtEndereco;
	private JNumberField txtControlador;
	private JLabel lblDescricao;
	private JButton btnCancel;
	private JButton btnOk;
	private JButton botaoVezes;
	private JButton botaoDividir;
	private JButton botaoMenos;
	private JButton botaoMais;
	private JPanel abaVariaveis;
	private JLabel lblControlador;
	private JLabel lblEndereco;
	private JLabel lblName;
	private JPanel pnlButtons;

	private TableModel tblAcoesModel;
	private String x = "x";
	private String oldX = "x";
	private String op = null;
	private String oldOp = null;
	private Vector<String> formatacao = new Vector<String>();

	private Supervisorio supervisorio;

	private Variable variable;
	private ComponentPojo componentPojo;

	public VariableWindow(Variable variable, ComponentPojo pojo) {
		super();
		this.variable = variable;
		supervisorio = Supervisorio.getInstance();
		componentPojo = pojo;
		supervisorio.setVariableWindow(this);
		initGUI();

	}

	private void initGUI() {
		try {
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setTitle("i2M - Variável");
			this.setResizable(false);
			{
				pnlBody = new JPanel();
				BorderLayout pnlBodyLayout = new BorderLayout();
				pnlBody.setLayout(pnlBodyLayout);
				getContentPane().add(pnlBody, BorderLayout.CENTER);
				{
					pnlAbas = new JTabbedPane();
					pnlBody.add(pnlAbas, BorderLayout.CENTER);
					{
						abaGeral = new JPanel();
						pnlAbas.addTab("Geral", null, abaGeral, null);
						abaGeral.setLayout(null);
						{
							lblName = new JLabel();
							abaGeral.add(lblName);
							lblName.setText("Nome:");
							lblName.setBounds(12, 15, 58, 14);
						}
						{
							txtName = new JTextField(variable.getName());
							abaGeral.add(txtName);
							txtName.setBounds(104, 12, 271, 21);
						}
						{
							lblEndereco = new JLabel();
							abaGeral.add(lblEndereco);
							lblEndereco.setText("Endereço:");
							lblEndereco.setBounds(12, 40, 106, 14);
						}
						{
							lblControlador = new JLabel();
							abaGeral.add(lblControlador);
							lblControlador.setText("Controlador");
							lblControlador.setBounds(12, 67, 106, 14);
						}
						{
							lblDescricao = new JLabel();
							abaGeral.add(lblDescricao);
							lblDescricao.setText("Descrição:");
							lblDescricao.setBounds(12, 114, 92, 14);
						}
						{
							txtDescricao = new JTextPane();
							abaGeral.add(txtDescricao);
							txtDescricao.setBounds(12, 134, 363, 88);
							txtDescricao.setBorder(BorderFactory
									.createEtchedBorder(BevelBorder.LOWERED));
							txtDescricao.setText(variable.getDescription());
						}
						{
							txtControlador = new JNumberField();
							abaGeral.add(txtControlador);
							txtControlador.setBounds(105, 64, 270, 21);
							txtControlador.setText(""
									+ (int) variable.getControllerAddress());
						}
						{
							txtEndereco = new JNumberField();
							abaGeral.add(txtEndereco);
							txtEndereco.setBounds(104, 37, 271, 21);
							txtEndereco.setText(""
									+ (int) variable.getAddress());
						}
						{
							jSeparator1 = new JSeparator();
							abaGeral.add(jSeparator1);
							jSeparator1.setBounds(12, 104, 363, 10);
						}
					}
					{
						abaVariaveis = new JPanel();
						pnlAbas.addTab("Valor Final", null, abaVariaveis, null);
						abaVariaveis.setLayout(null);
						{
							btnUndo = new JButton();
							abaVariaveis.add(btnUndo);
							btnUndo.setText("Desfazer");
							btnUndo.setBounds(151, 115, 114, 24);
							btnUndo.addMouseListener(new MouseAdapter() {
								public void mouseClicked(MouseEvent e) {
									btnUndoMouseClicked(e);
								}
							});
						}
						{
							campoValor = new JNumberField();
							abaVariaveis.add(campoValor);
							campoValor.setText("");
							campoValor.setBounds(283, 114, 94, 25);
							campoValor.setFocusable(false);
						}
						{
							botaoOk = new JButton();
							abaVariaveis.add(botaoOk);
							botaoOk.setText("Ok");
							botaoOk.setBounds(20, 115, 104, 24);
							botaoOk.setSize(114, 24);
							botaoOk.addMouseListener(new MouseAdapter() {
								public void mouseClicked(MouseEvent e) {
									botaoOkMouseClicked(e);
								}
							});
						}
						{
							jTextPane1 = new JTextPane();
							abaVariaveis.add(jTextPane1);
							if (variable.getEquation() != null) {
								jTextPane1.setText(variable.getEquation());
								StringTokenizer st = new StringTokenizer(
										jTextPane1.getText());
								st.nextToken();
								st.nextToken();
								x = oldX = st.nextToken();
							} else
								jTextPane1.setText("y = " + x);
							jTextPane1.setBounds(20, 20, 245, 83);
							jTextPane1.setEditable(false);
						}
						{
							jPanel1 = new JPanel();
							abaVariaveis.add(jPanel1);
							GridBagLayout jPanel1Layout = new GridBagLayout();
							jPanel1Layout.columnWidths = new int[] { 7, 7 };
							jPanel1Layout.rowHeights = new int[] { 7, 7 };
							jPanel1Layout.columnWeights = new double[] { 0.1,
									0.1 };
							jPanel1Layout.rowWeights = new double[] { 0.1, 0.1 };
							jPanel1.setLayout(jPanel1Layout);
							jPanel1.setBounds(283, 20, 94, 88);
							{
								botaoMais = new JButton();
								jPanel1.add(botaoMais, new GridBagConstraints(
										0, 0, 1, 1, 0.0, 0.0,
										GridBagConstraints.CENTER,
										GridBagConstraints.BOTH, new Insets(0,
												0, 0, 0), 0, 0));
								botaoMais.setText("+");
								botaoMais.setFont(new java.awt.Font("Tahoma",
										0, 16));
								botaoMais.addMouseListener(new MouseAdapter() {
									public void mouseClicked(MouseEvent e) {
										botaoMaisMouseClicked(e);
									}
								});
							}
							{
								botaoMenos = new JButton();
								jPanel1.add(botaoMenos, new GridBagConstraints(
										1, 0, 1, 1, 0.0, 0.0,
										GridBagConstraints.CENTER,
										GridBagConstraints.BOTH, new Insets(0,
												0, 0, 0), 0, 0));
								botaoMenos.setText("-");
								botaoMenos.setFont(new java.awt.Font("Tahoma",
										0, 16));
								botaoMenos.addMouseListener(new MouseAdapter() {
									public void mouseClicked(MouseEvent e) {
										botaoMenosMouseClicked(e);
									}
								});
							}
							{
								botaoDividir = new JButton();
								jPanel1.add(botaoDividir,
										new GridBagConstraints(0, 1, 1, 1, 0.0,
												0.0, GridBagConstraints.CENTER,
												GridBagConstraints.BOTH,
												new Insets(0, 0, 0, 0), 0, 0));
								botaoDividir.setText("/");
								botaoDividir.setFont(new java.awt.Font(
										"Tahoma", 0, 16));
								botaoDividir
										.addMouseListener(new MouseAdapter() {
											public void mouseClicked(
													MouseEvent e) {
												botaoDividirMouseClicked(e);
											}
										});
							}
							{
								botaoVezes = new JButton();
								jPanel1.add(botaoVezes, new GridBagConstraints(
										1, 1, 1, 1, 0.0, 0.0,
										GridBagConstraints.CENTER,
										GridBagConstraints.BOTH, new Insets(0,
												0, 0, 0), 0, 0));
								botaoVezes.setText("*");
								botaoVezes.setFont(new java.awt.Font("Tahoma",
										0, 16));
								botaoVezes.addMouseListener(new MouseAdapter() {
									public void mouseClicked(MouseEvent e) {
										botaoVezesMouseClicked(e);
									}
								});
							}
						}
					}
					{
						pnlAcoes = new JPanel();
						pnlAbas.addTab("Ações", null, pnlAcoes, null);
						BorderLayout pnlAcoesLayout = new BorderLayout();
						pnlAcoes.setLayout(pnlAcoesLayout);
						{
							jScrollPane1 = new JScrollPane();
							pnlAcoes.add(jScrollPane1, BorderLayout.CENTER);
							{
								tblAcoes = new MyTable();
								jScrollPane1.setViewportView(tblAcoes);
							}
						}
						{
							pnlAcoesSul = new JPanel();
							FlowLayout pnlAcoesSulLayout = new FlowLayout();
							pnlAcoes.add(pnlAcoesSul, BorderLayout.SOUTH);
							pnlAcoesSul
									.setPreferredSize(new java.awt.Dimension(
											389, 36));
							pnlAcoesSul.setLayout(pnlAcoesSulLayout);
							{
								btnAdd = new JButton();
								pnlAcoesSul.add(btnAdd);
								btnAdd.setText("Adicionar");
								btnAdd.setSize(97, 21);
								btnAdd.setPreferredSize(new java.awt.Dimension(
										97, 21));
								btnAdd.addActionListener(new ActionListener() {
									public void actionPerformed(ActionEvent evt) {
										btnAddActionPerformed(evt);
									}
								});
							}
							{
								btnExcluir = new JButton();
								pnlAcoesSul.add(btnExcluir);
								btnExcluir.setText("Excluir");
								btnExcluir
										.setPreferredSize(new java.awt.Dimension(
												97, 21));
							}
						}
					}
				}
			}
			{
				pnlButtons = new JPanel();
				getContentPane().add(pnlButtons, BorderLayout.SOUTH);
				pnlButtons.setPreferredSize(new java.awt.Dimension(394, 31));
				{
					btnOk = new JButton();
					pnlButtons.add(btnOk);
					btnOk.setText("OK");
					btnOk.setPreferredSize(new java.awt.Dimension(100, 21));
					btnOk.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent e) {
							btnOkMouseClicked(e);
						}
					});
				}
				{
					btnCancel = new JButton();
					pnlButtons.add(btnCancel);
					btnCancel.setText("Cancelar");
					btnCancel.setPreferredSize(new java.awt.Dimension(100, 21));
					btnCancel.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent e) {
							btnCancelMouseClicked(e);
						}
					});
				}
				this.updateActionsTbl();
			}

			pack();
			this.setSize(404, 323);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void updateActionsTbl() {

		ArrayList<Action> actions = new ArrayList<Action>(variable.getActions());

		String[][] data = new String[actions.size()][3];

		for (int i = 0; i < actions.size(); i++) {
			Action action = actions.get(i);
			data[i][0] = action.getName();
			data[i][1] = action.getOperation();
			data[i][2] = String.valueOf(action.getReference());
		}

		tblAcoesModel = new DefaultTableModel(data, new String[] { "Nome",
				"Condição", "Valor" });
		jScrollPane1.setViewportView(tblAcoes);
		tblAcoes.setModel(tblAcoesModel);

		tblAcoes.updateUI();

	}

	private void desfazer() {
		StringTokenizer st = new StringTokenizer(jTextPane1.getText());
		st.nextToken();
		st.nextToken();
		StringBuilder result = new StringBuilder();
		if (!x.equals(oldX)) {
			x = oldX;
			campoValor.setFocusable(false);
			this.escreve();
		} else
			try {
				String[] exp = st.nextElement().toString().split(
						"\\" + formatacao.lastElement());
				for (int i = 0; i < exp.length - 1; i++) {
					result.append(exp[i]);
					if (i + 2 < exp.length) {
						result.append(formatacao.lastElement());
					}
				}
				char[] expression = result.toString().toCharArray();
				result = new StringBuilder();

				if (x.trim().equals("x")) {
					oldX = x = "x";
				} else {
					for (int i = 0; i < expression.length; i++) {
						if (i != 0) {
							result.append(expression[i]);
						}
					}
					formatacao.remove(formatacao.size() - 1);
					oldX = x = result.toString();
				}
				this.escreve();
			} catch (NoSuchElementException e) {
			}
	}

	private void escreve() {
		jTextPane1.setText("y = " + x);
	}

	private void opButtons() {
		if (!campoValor.getText().trim().equals("")) {
			oldX = x + campoValor.getText() + ")";
			x = "(" + oldX + op;
			campoValor.setText("");
			formatacao.add(oldOp);
		} else {
			x = "(" + oldX + op;
		}
		this.escreve();
		campoValor.setFocusable(true);
		campoValor.requestFocus();
	}

	private void btnAddActionPerformed(ActionEvent evt) {
		ActionWindow actionWindow = new ActionWindow(variable);
		actionWindow.setVisible(true);
	}

	private void btnUndoMouseClicked(MouseEvent evt) {
		this.desfazer();
	}

	private void botaoOkMouseClicked(MouseEvent evt) {
		if (!campoValor.getText().equals("")) {
			x = x + campoValor.getText() + ")";
			oldX = x;
			this.escreve();
			campoValor.setText("");
			campoValor.setFocusable(false);
			formatacao.add(op);
		}
	}

	private void botaoMaisMouseClicked(MouseEvent evt) {
		oldOp = op;
		op = "+";
		this.opButtons();
	}

	private void botaoMenosMouseClicked(MouseEvent evt) {
		oldOp = op;
		op = "-";
		this.opButtons();
	}

	private void botaoDividirMouseClicked(MouseEvent evt) {
		oldOp = op;
		op = "/";
		this.opButtons();
	}

	private void btnOkMouseClicked(MouseEvent evt) {
		supervisorio.remoteVariableBuildTree();
		if (txtName.getText() == null || txtName.getText().trim().equals("")) {
			JOptionPane.showMessageDialog(null, "Insira um nome!");
			return;
		}

		String name = txtName.getText();
		String address = txtEndereco.getText();
		String controllerAddress = txtControlador.getText();
		String description = txtDescricao.getText();
		String equation = jTextPane1.getText();

		boolean status = supervisorio.createOrUpdateVariable(variable,
				componentPojo, name, address, controllerAddress, description,
				equation);

		if (status) {
			supervisorio.updateComponentVariables();
			dispose();
		} else
			JOptionPane.showMessageDialog(null, "Não atualizou");
	}

	private void botaoVezesMouseClicked(MouseEvent evt) {
		oldOp = op;
		op = "*";
		this.opButtons();
	}

	private void btnCancelMouseClicked(MouseEvent e) {
		this.dispose();
	}

}
